package com.ce.source.analysis.thread;


import java.io.*;
import java.nio.charset.Charset;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ：前世小和尚（xiaopingzhang8@creditease.cn）
 * @Description ：
 * @ClassName ：ReadFile
 * @Company ：普信恒业科技发展（北京）有限公司
 * @date ：2018/3/14 18:10
 */
public class ReadFile {

    public static volatile Integer offset = 0;
    public static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) throws Exception {
        String path = "e://技术点.txt";
        final StringBuffer sb = new StringBuffer();
        final CountDownLatch latch = new CountDownLatch(15);
        File file = new File(path);
        try {
            final char[] buf = new char[10];
            final BufferedReader reader = new BufferedReader(new FileReader(file));
//            while (reader.read(buf, 0, buf.length) != -1) {
//                sb.append(new String(buf));
//            }
            final Long length = file.length();
            double len = Math.ceil(length.doubleValue() / 10);
            ExecutorService service = Executors.newFixedThreadPool(4);
            for (long i = 0L; i < len; i++) {
                service.execute(new Runnable() {
                    public void run() {
                        try {
                            synchronized (sb) {
                                int len = length - (count.get() * buf.length) > buf.length ? buf.length : (int) (length - (count.get() * buf.length));
                                count.incrementAndGet();
                                if (reader.read(buf, 0, len) != -1) {
                                    sb.append(new String(buf));
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            latch.countDown();
                        }
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        latch.await();
        System.out.println(sb.toString());


    }

    /**
     * 方式一：采用RandomAccessFile
     *
     * @param path
     * @param sb
     */
    private static void method1(String path, StringBuffer sb) {
        try {
            final CountDownLatch latch = new CountDownLatch(4);
            File file = new File(path);
            Long length = file.length();
            final byte[] buf = new byte[100];
            final RandomAccessFile raf = new RandomAccessFile(file, "r");
            double len = Math.ceil(length.doubleValue() / 100);
            ExecutorService service = Executors.newFixedThreadPool(length.intValue() / 100);
            for (int i = 0; i < len; i++) {
                service.execute(new Runnable() {
                    public void run() {
                        try {
                            synchronized (raf) {
                                raf.seek(offset);
                                if (raf.read(buf) != -1) {
                                    System.out.println(new String(buf, "utf-8"));
                                }
                                ;
                                synchronized (offset) {
                                    offset = offset + 100;
                                }
                                latch.countDown();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                });
            }
            latch.await();
            System.out.println(sb.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
